package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommentResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/cretePayment")
    public CommentResult createPayment(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        if (result > 0) {
            return new CommentResult(200, "插入成功,返回结果" + result + "\t 服务端口：" + serverPort);
        } else
            return new CommentResult(400, "插入失败");
    }

    @GetMapping("/getPaymentById/{id}")
    public CommentResult<Payment> getPaymentById(@PathVariable(value = "id") Long id) {
        Payment paymentById = paymentService.getPaymentById(id);
        if (paymentById != null) {
            return new CommentResult(200, "查询成功" + "服务端口：" + serverPort, paymentById);
        } else {
            return new CommentResult(400, "查询数据失败", null);
        }
    }

    @GetMapping("/getProviderInfo")
    public CommentResult<ServiceInstance> getProviderInfo() {
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance : instances) {
            log.info("serviedID:" + instance.getServiceId(), "serviedHost:" + instance.getHost(), "post:" + instance.getPort());
        }
        return new CommentResult(200, "服务信息", instances);
    }
    @GetMapping(value = "/payment/lb")
    public String getPaymentLB()
    {
        return serverPort;
    }
}
